const express = require('express')
const router = express.Router()
const { getLessonContent, getLessonContentById, getLessonAudio,getCourseID } = require('../utils/resourceScanner')
const db = require('../utils/database')

// 返回mp3文件的base64编码
router.get('/:coursePath/audio/:lessonId', async (req, res) => {
  try {
    const { coursePath, lessonId } = req.params
    const audio = await getLessonAudio(coursePath, lessonId)
    if (!audio) {
      return res.status(404).json({ message: 'Lesson audio not found' })
    }
    
    // Return lesson audio
    // 转化为base64编码
    const audioBase64 = Buffer.from(audio).toString('base64');
    res.set('Content-Length', audioBase64.length);
    res.send(audioBase64);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching lesson content', error: error.message })
  }
})

// Get lesson content by course path and lesson ID
router.get('/:coursePath/:lessonId', async (req, res) => {
  try {
    const { coursePath, lessonId } = req.params
    
    // 获取课程ID
    let courseId = getCourseID(coursePath);
    getLessonContent(coursePath, lessonId).then(content => {
      if (!content) {
        console.error('Lesson content not found')
        return res.status(404).json({ message: 'Lesson content not found' })
      }
      
      // Return lesson data with content included
      res.json({
        id: lessonId,
        courseId: courseId,
        title: content.length > 0 ? content[0].english : `Lesson ${lessonId}`,
        description: ` ${content[0].chinese}`,
        content: content
      })
    }).catch(error => {
      console.error(error)
      res.status(500).json({ message: 'Error fetching lesson content', error: error.message })
    })
  } catch (error) {
    console.error(error)
    res.status(500).json({ message: 'Error fetching lesson content', error: error.message })
  }
})

// Get lesson content by lesson ID only (searches across all courses)
router.get('/:lessonId', async (req, res) => {
  try {
    const { lessonId } = req.params
    const result = await getLessonContentById(lessonId)
    
    if (!result) {
      return res.status(404).json({ message: 'Lesson content not found' })
    }
    
    // 获取课程ID
    const courseQuery = `SELECT id FROM courses WHERE path = ?`
    db.get(courseQuery, [result.coursePath], (err, courseRow) => {
      if (err || !courseRow) {
        return res.status(404).json({ message: 'Course not found' })
      }
      
      const courseId = courseRow.id
      
      // Return lesson data with content included
      res.json({
        id: lessonId,
        courseId: courseId,
        title: result.content.length > 0 ? result.content[0].english : `Lesson ${lessonId}`,
        description: `第 ${lessonId} 课`,
        content: result.content
      })
    })
  } catch (error) {
    res.status(500).json({ message: 'Error fetching lesson content', error: error.message })
  }
})

module.exports = router